// 本地存储管理工具
// 用于管理订单、地址、商品等数据的本地缓存

// 存储键名常量
const STORAGE_KEYS = {
  USER_INFO: 'userInfo',
  TOKEN: 'token',
  REFRESH_TOKEN: 'refreshToken',
  WECHAT_USER_INFO: 'wechatUserInfo',
  LOGIN_STATUS: 'loginStatus',
  OPENID: 'openid',
  SESSION_KEY: 'sessionKey',
  TOKEN_TYPE: 'tokenType',
  EXPIRES_IN: 'expiresIn',
  ADDRESSES: 'addresses',
  SELECTED_ADDRESS: 'address',
  ORDERS: 'orders',
  PRODUCTS: 'products',
  CART: 'cart',
  SETTINGS: 'settings'
}

// 通用存储方法
const storage = {
  // 设置数据
  set(key, value) {
    try {
      uni.setStorageSync(key, JSON.stringify(value))
      return true
    } catch (error) {
      console.error('存储数据失败:', error)
      return false
    }
  },
  
  // 获取数据
  get(key, defaultValue = null) {
    try {
      const value = uni.getStorageSync(key)
      return value ? JSON.parse(value) : defaultValue
    } catch (error) {
      console.error('获取数据失败:', error)
      return defaultValue
    }
  },
  
  // 删除数据
  remove(key) {
    try {
      uni.removeStorageSync(key)
      return true
    } catch (error) {
      console.error('删除数据失败:', error)
      return false
    }
  },
  
  // 清空所有数据
  clear() {
    try {
      uni.clearStorageSync()
      return true
    } catch (error) {
      console.error('清空数据失败:', error)
      return false
    }
  }
}

// 用户信息管理
export const userStorage = {
  // 保存用户信息
  setUserInfo(userInfo) {
    return storage.set(STORAGE_KEYS.USER_INFO, userInfo)
  },
  
  // 获取用户信息
  getUserInfo() {
    return storage.get(STORAGE_KEYS.USER_INFO, {})
  },
  
  // 清除用户信息
  clearUserInfo() {
    return storage.remove(STORAGE_KEYS.USER_INFO)
  },
  
  // 保存token
  setToken(token) {
    return storage.set(STORAGE_KEYS.TOKEN, token)
  },
  
  // 获取token
  getToken() {
    return storage.get(STORAGE_KEYS.TOKEN, '')
  },
  
  // 清除token
  clearToken() {
    return storage.remove(STORAGE_KEYS.TOKEN)
  },
  
  // 微信登录相关存储
  // 保存刷新token
  setRefreshToken(refreshToken) {
    return storage.set(STORAGE_KEYS.REFRESH_TOKEN, refreshToken)
  },
  
  // 获取刷新token
  getRefreshToken() {
    return storage.get(STORAGE_KEYS.REFRESH_TOKEN, '')
  },
  
  // 清除刷新token
  clearRefreshToken() {
    return storage.remove(STORAGE_KEYS.REFRESH_TOKEN)
  },
  
  // 保存微信用户信息
  setWechatUserInfo(wechatUserInfo) {
    return storage.set(STORAGE_KEYS.WECHAT_USER_INFO, wechatUserInfo)
  },
  
  // 获取微信用户信息
  getWechatUserInfo() {
    return storage.get(STORAGE_KEYS.WECHAT_USER_INFO, {})
  },
  
  // 清除微信用户信息
  clearWechatUserInfo() {
    return storage.remove(STORAGE_KEYS.WECHAT_USER_INFO)
  },
  
  // 设置登录状态
  setLoginStatus(isLoggedIn) {
    return storage.set(STORAGE_KEYS.LOGIN_STATUS, isLoggedIn)
  },
  
  // 获取登录状态
  getLoginStatus() {
    return storage.get(STORAGE_KEYS.LOGIN_STATUS, false)
  },
  
  // 清除登录状态
  clearLoginStatus() {
    return storage.remove(STORAGE_KEYS.LOGIN_STATUS)
  },
  
  // 保存openid
  setOpenid(openid) {
    return storage.set(STORAGE_KEYS.OPENID, openid)
  },
  
  // 获取openid
  getOpenid() {
    return storage.get(STORAGE_KEYS.OPENID, '')
  },
  
  // 清除openid
  clearOpenid() {
    return storage.remove(STORAGE_KEYS.OPENID)
  },
  
  // 保存session_key
  setSessionKey(sessionKey) {
    return storage.set(STORAGE_KEYS.SESSION_KEY, sessionKey)
  },
  
  // 获取session_key
  getSessionKey() {
    return storage.get(STORAGE_KEYS.SESSION_KEY, '')
  },
  
  // 清除session_key
  clearSessionKey() {
    return storage.remove(STORAGE_KEYS.SESSION_KEY)
  },
  
  // 保存token类型
  setTokenType(tokenType) {
    return storage.set(STORAGE_KEYS.TOKEN_TYPE, tokenType)
  },
  
  // 获取token类型
  getTokenType() {
    return storage.get(STORAGE_KEYS.TOKEN_TYPE, 'Bearer')
  },
  
  // 清除token类型
  clearTokenType() {
    return storage.remove(STORAGE_KEYS.TOKEN_TYPE)
  },
  
  // 保存过期时间
  setExpiresIn(expiresIn) {
    return storage.set(STORAGE_KEYS.EXPIRES_IN, expiresIn)
  },
  
  // 获取过期时间
  getExpiresIn() {
    return storage.get(STORAGE_KEYS.EXPIRES_IN, 7200)
  },
  
  // 清除过期时间
  clearExpiresIn() {
    return storage.remove(STORAGE_KEYS.EXPIRES_IN)
  },
  
  // 完整登录信息保存（包含token、用户信息等）
  setLoginData(loginData) {
    const { token, refreshToken, userInfo, wechatUserInfo, openid, sessionKey, tokenType, expiresIn } = loginData
    
    if (token) this.setToken(token)
    if (refreshToken) this.setRefreshToken(refreshToken)
    if (userInfo) this.setUserInfo(userInfo)
    if (wechatUserInfo) this.setWechatUserInfo(wechatUserInfo)
    if (openid) this.setOpenid(openid)
    if (sessionKey) this.setSessionKey(sessionKey)
    if (tokenType) this.setTokenType(tokenType)
    if (expiresIn) this.setExpiresIn(expiresIn)
    
    this.setLoginStatus(true)
    return true
  },
  
  // 清除所有登录相关数据
  clearAllLoginData() {
    this.clearToken()
    this.clearRefreshToken()
    this.clearUserInfo()
    this.clearWechatUserInfo()
    this.clearOpenid()
    this.clearSessionKey()
    this.clearTokenType()
    this.clearExpiresIn()
    this.clearLoginStatus()
    return true
  },
  
  // 检查是否已登录
  isLoggedIn() {
    const token = this.getToken()
    const loginStatus = this.getLoginStatus()
    return !!(token && loginStatus)
  }
}

// 地址管理
export const addressStorage = {

  getSelectedAddress() {
    return storage.get(STORAGE_KEYS.SELECTED_ADDRESS)
  },

  setSelectedAddress(address) {
    return storage.set(STORAGE_KEYS.SELECTED_ADDRESS, address)
  }
}

// 订单管理
export const orderStorage = {
  // 保存订单列表
  setOrders(orders) {
    return storage.set(STORAGE_KEYS.ORDERS, orders)
  },
  
  // 获取订单列表
  getOrders() {
    return storage.get(STORAGE_KEYS.ORDERS, [])
  },
  
  // 添加订单
  addOrder(order) {
    const orders = this.getOrders()
    const newOrder = {
      id: Date.now().toString(),
      orderNo: 'PB' + Date.now(),
      ...order,
      createTime: new Date().toISOString(),
      status: 'pending' // pending, paid, shipped, delivered, cancelled
    }
    orders.unshift(newOrder) // 新订单放在最前面
    return storage.set(STORAGE_KEYS.ORDERS, orders)
  },
  
  // 更新订单
  updateOrder(orderId, orderData) {
    const orders = this.getOrders()
    const index = orders.findIndex(order => order.id === orderId)
    if (index !== -1) {
      orders[index] = {
        ...orders[index],
        ...orderData,
        updateTime: new Date().toISOString()
      }
      return storage.set(STORAGE_KEYS.ORDERS, orders)
    }
    return false
  },
  
  // 获取订单详情
  getOrderById(orderId) {
    const orders = this.getOrders()
    return orders.find(order => order.id === orderId) || null
  },
  
  // 根据状态筛选订单
  getOrdersByStatus(status) {
    const orders = this.getOrders()
    return status === 'all' ? orders : orders.filter(order => order.status === status)
  },
  
  // 取消订单
  cancelOrder(orderId) {
    return this.updateOrder(orderId, { status: 'cancelled' })
  },
  
  // 确认收货
  confirmOrder(orderId) {
    return this.updateOrder(orderId, { status: 'delivered' })
  }
}

// 商品管理
export const productStorage = {
  // 保存商品列表
  setProducts(products) {
    return storage.set(STORAGE_KEYS.PRODUCTS, products)
  },
  
  // 获取商品列表
  getProducts() {
    return storage.get(STORAGE_KEYS.PRODUCTS, [])
  },
  
  // 获取商品详情
  getProductById(productId) {
    const products = this.getProducts()
    return products.find(product => product.id === productId) || null
  },
  
  // 搜索商品
  searchProducts(keyword) {
    const products = this.getProducts()
    return products.filter(product => 
      product.name.includes(keyword) || 
      product.description.includes(keyword)
    )
  }
}

// 购物车管理（虽然不需要购物车功能，但保留接口以备扩展）
export const cartStorage = {
  // 获取购物车
  getCart() {
    return storage.get(STORAGE_KEYS.CART, [])
  },
  
  // 清空购物车
  clearCart() {
    return storage.set(STORAGE_KEYS.CART, [])
  }
}

// 应用设置管理
export const settingsStorage = {
  // 保存设置
  setSettings(settings) {
    return storage.set(STORAGE_KEYS.SETTINGS, settings)
  },
  
  // 获取设置
  getSettings() {
    return storage.get(STORAGE_KEYS.SETTINGS, {
      theme: 'light',
      language: 'zh-CN',
      notifications: true
    })
  },
  
  // 更新单个设置
  updateSetting(key, value) {
    const settings = this.getSettings()
    settings[key] = value
    return this.setSettings(settings)
  }
}

// 导出默认存储对象
export default {
  storage,
  user: userStorage,
  address: addressStorage,
  order: orderStorage,
  product: productStorage,
  cart: cartStorage,
  settings: settingsStorage,
  STORAGE_KEYS
}